import base64
import uuid
from enum import Enum

from PyQt5 import QtCore, QtGui, QtWidgets
from collections import namedtuple

import numpy as np
import mediapipe as mp
import threading
import sys


class tempType(Enum):
    LEFT_TEMP = 1
    RIGHT_TEMP = 2


MIN_DISTANCE = 20  # 单位毫米
MAX_DISTANCE = 600  # 单位毫米
RESOULTION_X = 640.0  # 标定时的分辨率
RESOULTION_Y = 480.0  # 标定时的分辨率

# 相机镜头的矫正参数，用于cv2.undistort()的输入之一
CAM_DVEC = np.array([-0.33354, 0.00924849, -0.000457208, -0.00215353, 0.0])

# 生成点云使用的相机参数
intrinsic_params = namedtuple("intrinsic_params", ["c_x", "c_y", "f_x", "f_y", "width", "height"])
intrinsic_params.width = 640
intrinsic_params.height = 480
intrinsic_params.c_x = 326.64
intrinsic_params.c_y = 241.838
intrinsic_params.f_x = 578.154
intrinsic_params.f_y = 578.154

# 人脸识别配置
mp_drawing = mp.solutions.drawing_utils
mp_face_detction = mp.solutions.face_detection
mp_face_mesh = mp.solutions.face_mesh
face_mesh = mp_face_mesh.FaceMesh(static_image_mode=True, max_num_faces=1, min_detection_confidence=0.5)
drawing_spec = mp_drawing.DrawingSpec(thickness=0, circle_radius=0, color=(255, 255, 255))
drawing_spec1 = mp_drawing.DrawingSpec(thickness=2, circle_radius=1, color=(153, 204, 102))

left_temporal_indexs = [103, 104, 63, 46, 156, 143, 34, 127, 162, 21, 54]

left_temporal_drawlist = [[103, 104], [104, 63], [63, 46], [46, 156], [156, 143], [143, 34], [34, 127], [127, 162]
    , [162, 21], [21, 54], [54, 103]]
right_temporal_indexs = [264, 372, 383, 300, 293, 333, 332, 284, 251, 389, 356]
right_temporal_drawlist = [[264, 372], [372, 383], [383, 300], [300, 293], [293, 333], [333, 332], [332, 284], [284, 251]
    , [251, 389], [389, 356], [356, 264]]

none_collect_styleSheet = "color:rgb(255, 255, 255);background:rgb(88, 88, 88)"
start_collect_styleSheet = "color:rgb(153, 204, 102);background:rgb(88, 88, 88)"
end_collect_styleSheet = "color:rgb(255, 255, 255);background:rgb(153, 204, 102)"


def getUuid():
    r_uuid = base64.urlsafe_b64encode(uuid.uuid4().bytes)
    return r_uuid.replace('=', '')


def alert(msg=u"msg", title=u"警告", icon=QtWidgets.QMessageBox.Warning, button_text=u"确定"):
    # NOTE 生成 Qt 警告窗口
    msg_box = QtWidgets.QMessageBox()
    msg_box.setIcon(icon)
    msg_box.setWindowTitle(title)
    msg_box.setText(msg)
    msg_box.addButton(button_text, QtWidgets.QMessageBox.AcceptRole)
    msg_box.exec_()


def convertDepthToPoint(depimg):
    x, y = np.meshgrid(range(intrinsic_params.width), range(intrinsic_params.height))
    x = x.astype(np.float32) - intrinsic_params.c_x
    y = y.astype(np.float32) - intrinsic_params.c_y

    poi_z = depimg.copy()

    poi_x = poi_z * x / intrinsic_params.f_x  # X=Z*(u-cx)/fx
    poi_y = poi_z * y / intrinsic_params.f_y  # Y=Z*(v-cy)/fy
    poi = np.array([poi_x.ravel(), poi_y.ravel(), poi_z.ravel()]).T
    return poi
